package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heim.file.MinIoTemplate;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.ProtostuffUtil;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.ContextLoaderListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author :28169
 * @date : 2022/7/20 1:41
 */
@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private IArticleClient iArticleClient;

    @Override
    @Async   //异步
    public void autoScanWmNews(Long newsId) throws Exception {

        //入参判断
        if (newsId==null){
            log.warn("newsId为空");
            return;
        }
    //查询新闻
        WmNews byId = wmNewsService.getById(newsId);
        if (byId==null){
            log.warn("新闻"+newsId+"为空");
            return;
        }

        //提取新闻文字
        String title = byId.getTitle();
        String content = byId.getContent();
        String text = getText(title, content);

        //提取新闻图片
        String images = byId.getImages();
        List<byte[]> imagesList = getImages(images, content);
        //文字审核
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean checkResult = checkResult(textScan, null, newsId.intValue());
        if (!checkResult){
            log.warn("文字审核失败");
            return;
        }
        //调用图片审核
        Map imageScan = greenImageScan.imageScan(imagesList);
        Boolean checkResult1 = checkResult(imageScan, null, newsId.intValue());
        if (!checkResult1){
            log.warn("图片审核失败");
            return;
        }

        //远程调用ArticleClient保存文件N

        ArticleDto dto=wmNews2ArticleDto(byId) ;
        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        if (responseResult==null|| responseResult.getCode()!=200){
            log.warn("保存失败");
            return;

        }
        Long articleId = (Long) responseResult.getData();
        //将article回写wmNews
        updateWmNews(9,"审核通过",articleId,newsId.intValue());
    }
    private String getText(String title,String content){
        if (StringUtils.isEmpty(content)){
            return title;
        }
        //获取content中的文字
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)){
            return title;

        }
        StringBuilder builder = new StringBuilder();
        for (Map map : maps) {

            if (CollectionUtils.isEmpty(map)){
                continue;
            }
            Object type = map.get("type");
            if ("test".equals(type)){
                String value = (String) map.get("value");
                builder.append(value);
            }
        }
//content和title组合
        builder.append("_").append(title);

        //返回组合的结果
return builder.toString();

    }
    private List<byte[]> getImages(String images,String content){

        ArrayList<String> arrayList = new ArrayList<>();
        //先对参数判空
        if (StringUtils.isNotBlank(images)){
          //不为空就提取图片
            String[] split = images.split(",");//获得数组
            if (ArrayUtils.isNotEmpty(split)){

                //不为空将split转成对应集合
                List<String> asList = Arrays.asList(split);

                arrayList.addAll(asList);
            }
        }

        if (StringUtils.isNotBlank(content)){
        //不为空提取内容
            //先把content转换成集合
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)){
                 //不为空先循环
                for (Map map : maps) {
                    if (CollectionUtils.isEmpty(map)){
                        continue;
                    }
                    Object type = map.get("type");
                    //如果类型是图片类型
                    if ("image".equals(type)){
                        String value = (String) map.get("value");

                     arrayList.add(value);
                    }
                }
            }
        }
        ArrayList<byte[]> bytes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(arrayList)){
            for (String s : arrayList) {
                if (StringUtils.isEmpty(s)){
                    continue;
                }
                //遍历完下载下来
                byte[] bytes1 = minIoTemplate.downLoadFile(s);
                bytes.add(bytes1);

            }
        }
return bytes;
    }
    //更新方法
    private Boolean updateWmNews(Integer status,String reason,Long articleId,Integer newsId){
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        if (articleId!=null){
            wmNews.setArticleId(articleId);
        }
        return wmNewsService.updateById(wmNews);
    }
    //处理text结果
    private Boolean checkResult(Map result,Long articleId,Integer newsId){
        if (CollectionUtils.isEmpty(result)){
            log.warn("审核为空");
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)){
            return true;
        }else if ("block".equals(suggestion)){
            updateWmNews(2,"未通过",articleId,newsId);
            return false;
        }else if ("review".equals(suggestion)){
            updateWmNews(3,"转人工",articleId,newsId);
            return false;
        }
        return true;
    }
    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private WmUserService wmUserService;
    private ArticleDto wmNews2ArticleDto(WmNews wmNews){
        if (wmNews==null){
            return null;
        }
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setLayout(wmNews.getType());
//频道名称
        Integer channelId = wmNews.getChannelId();
        if (channelId!=null){
            WmChannel channel = wmChannelService.getById(channelId);
            if (channel!=null){
                articleDto.setChannelName(channel.getName());

            }


        }
//作者名
        Integer userId = wmNews.getUserId();
        if (userId!=null){
            articleDto.setAuthorId(userId.longValue());
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser!=null){
                articleDto.setAuthorName(wmUser.getName());
            }

        }


        return articleDto;
    }
@Autowired
    private IScheduleClient iScheduleClient;
    public void getTask(){
        ResponseResult responseResult = iScheduleClient.poll();
        if (responseResult!=null||responseResult.getCode()!=200){
            return;
        }
        String data = (String) responseResult.getData();
        if (StringUtils.isEmpty(data)){
            log.warn("没有消费的任务");
            return;
        }
        Task task = JSON.parseObject(data, Task.class);
        if (task==null){
            log.warn("没有消费的任务");
            return;
        }
        byte[] parameters = task.getParameters();
        WmNews deserialize = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (deserialize==null){
            log.warn("参数缺失");
            return;
        }

        try {
            autoScanWmNews(deserialize.getId().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
